package com.cloudfun.campusshare.util.haier;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class UhomeUtils {

    private static String APP_ID = "SV-QLKJ545-0000";

    private static String APP_KEY = "ca11183ad4b15dbe686892c09bf3cd3c";

    private static String APP_KEY_PROD = "ad95ee74c2d94644a075eb81d72391a8";

    private static String DEVICEID = "869696045234718";

    private static String DEVICEID_PROD = "869270044188620";

    private static String DEVICEID_XIAOLIAN = "865374034911324";



    @SneakyThrows
    public static String getSign(String appId, String appKey, String timestamp, String body,String url){
        URL urlObj = new URL(url);
        url=urlObj.getPath();
        appKey = appKey.trim();
        appKey = appKey.replaceAll("\"", "");
        if (body != null) {
            body = body.trim();
        }
        if (!body.equals("")) {
            body = body.replaceAll(" ", "");
            body = body.replaceAll("\t", "");
            body = body.replaceAll("\r", "");
            body = body.replaceAll("\n", "");
        }
        log.info("body:"+body);
        StringBuffer sb = new StringBuffer();
        sb.append(url).append(body).append(appId).append(appKey).append(timestamp);

        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            bytes = md.digest(sb.toString().getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return BinaryToHexString(bytes);
    }

    public static  String getSign(String systemId, String systemKey, String timestamp) {
        systemKey = systemKey.trim();
        systemKey = systemKey.replaceAll("\"", "");

        StringBuffer sb = new StringBuffer();
        sb.append(systemId).append(systemKey).append(timestamp);
        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            bytes = md.digest(sb.toString().getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BinaryToHexString(bytes);
    }

    public static String BinaryToHexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        String hexStr = "0123456789abcdef";
        for (int i = 0; i < bytes.length; i++) {
            hex.append(String.valueOf(hexStr.charAt((bytes[i] & 0xF0) >> 4)));
            hex.append(String.valueOf(hexStr.charAt(bytes[i] & 0x0F)));
        }
        return hex.toString();
    }

    public static HttpHeaders getBaseHeaders(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("appVersion","0.0.1");
        headers.set("clientId","GandaoPlat20191102");
        headers.set("sequenceId","2019110901010");
        headers.set("language","zh-cn");
        headers.set("timezone","8");
        return headers;
    }

    public static String Execute(String url, String body){

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("appId",APP_ID);
        headers.set("appKey",APP_KEY_PROD);
        headers.set("appVersion","0.0.1");
        headers.set("clientId","GandaoPlat20191102");
        headers.set("sequenceId","2019110901010");
        long time = System.currentTimeMillis();
        headers.set("timestamp",String.valueOf(time));
        headers.set("language","zh-cn");
        headers.set("timezone","8");

        String sign = getSign(APP_ID,APP_KEY_PROD,String.valueOf(time),body,url);
        headers.set("sign",sign);


        HttpEntity<String> request = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
        log.info("execute result: " + response.getBody());


        return response.getBody();
    }



    public static void testOperate(){

        String url = "https://uws.haier.net/stdudse/v2/modfier/operate";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("appId",APP_ID);
        headers.set("appKey",APP_KEY);
        headers.set("appVersion","0.0.1");
        headers.set("clientId","123123");
        headers.set("sequenceId","2019110901010");
        long time = System.currentTimeMillis();
        headers.set("timestamp",String.valueOf(time));
        headers.set("language","zh-cn");
        headers.set("timezone","8");

        OperateParam param = new OperateParam();
        param.setImei("869696045234718");
        param.setCmdName("grCommonWashCW");
        Map<String,String> cmdMap = new HashMap<>();
        cmdMap.put("laundryCycleCW","1");
        cmdMap.put("heatingStatus40","false");
        cmdMap.put("heatingStatus60","false");
        cmdMap.put("quietRinseStatus","false");
        cmdMap.put("speedUpStatus","false");
        param.setCmdArgs(cmdMap);
        String jsonString = JSONObject.toJSONString(param);
        String sign = getSign(APP_ID,APP_KEY,String.valueOf(time),jsonString,url);
        headers.set("sign",sign);


        HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
        System.out.println(response.getBody());

    }

    public static void test(){
        String url = "https://uws.haier.net/stdudse/v2/modfier/operate";
//        String url = "https://uws.haier.net/stdudse/v2/modfier/getAttributeByName";
//        String url = "https://uws.haier.net/stdudse/v2/getCautionList";
        long time = System.currentTimeMillis();
        System.out.println(time);
//        String body = "{\n" +
//                "\t\"deviceId\":\"869696045234718\",\n" +
//                "\t\"cmdName\":\"grCommonWashCW\",\n" +
//                "\t\"cmdArgs\":{\"laundryCycleCW\":\"5\",\"heatingStatus40\":\"false\",\"heatingStatus60\":\"false\",\"quietRinseStatus\":\"false\",\"speedUpStatus\":\"false\"}\n" +
//                "}";
//        String body = "{\n" +
//                "\t\"deviceId\":\"869696045234718\",\n" +
//                "\t\"attributeName\":\"heatingStatus40\"\n" +
//                "}";;
//        String body = "{\n" +
//                "\t\"deviceId\":\"869270044188620\",\n" +
//                "\t\"cmdArgs\":{\"returnStandby\":\"1\"}\n" +
//                "}";
        String body = "{\n" +
                "\t\"deviceId\":\"869696045234718\",\n" +
                "\t\"cmdName\":\"grCommonSetCD\",\n" +
                "\t\"cmdArgs\":{\"tempLevel\":1,\"waitingTime\":3,\"dryTime\":30,\"startEnabled\":\"true\"}\n" +
                "}";
//        String body = "{\n" +
//                "\t\"deviceId\":\"869696045234718\"\n" +
//                "}";

        String sign = getSign(APP_ID,APP_KEY,String.valueOf(time),body,url);
        System.out.println(sign);

    }

    public static void main(String[] args){

//        String url = "https://uws.haier.net/stdudse/v2/modfier/getAttributeByName";
//
//        Map<String,String> map = new HashMap<>();
//        map.put("imei","869696045234718");
//        map.put("attributeName","onOffStatus");
//        String body = JSONObject.toJSONString(map);
//        Execute(url,body);

//        OperateParam param = new OperateParam();
//        param.setImei("869696045234718");
//        param.setCmdName("grCommonWashCW");
//        Map<String,String> cmdMap = new HashMap<>();
//        cmdMap.put("laundryCycleCW","2");
//        cmdMap.put("heatingStatus40","false");
//        cmdMap.put("heatingStatus60","false");
//        cmdMap.put("quietRinseStatus","false");
//        cmdMap.put("speedUpStatus","false");
//        param.setCmdArgs(cmdMap);
//        String jsonString = JSONObject.toJSONString(param);
//        log.info("imei: " + "869696045234718");
//        log.info("body: " + jsonString);
//
//        String url = "https://uws.haier.net/stdudse/v2/modfier/operate";
//        String result = UhomeUtils.Execute(url,jsonString);
//        log.info("result: " + result);

        test();

    }

}
